<template>
  <Dialog title="分类管理" v-model="dialogVisible" width="800px">
    <div class="mb-4">
      <el-button type="primary" @click="openCategoryForm('create')">
        <Icon icon="ep:plus" />新增分类
      </el-button>
    </div>
    
    <el-table v-loading="loading" :data="categoryList">
      <el-table-column label="分类名称" prop="name" />
      <el-table-column label="描述" prop="description" show-overflow-tooltip />
      <el-table-column label="绘本数量" prop="bookCount" width="100" align="center" />
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
        align="center"
      />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="openCategoryForm('update', scope.row)"
          >
            <Icon icon="ep:edit" />修改
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDeleteCategory(scope.row.id)"
          >
            <Icon icon="ep:delete" />删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
  
  <!-- 分类表单弹窗 -->  
  <CategoryForm ref="categoryFormRef" @success="getCategoryList" />
</template>

<script setup lang="ts">
import { getBookCategories, deleteBookCategory } from '@/api/miniprogram/book'
import CategoryForm from './CategoryForm.vue'
import Dialog from '@/components/Dialog/src/Dialog.vue'
import { dateFormatter } from '@/utils/formatTime'

/** 分类管理弹窗 */
defineOptions({ name: 'CategoryDialog' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(false) // 列表的加载中
const categoryList = ref<any[]>([]) // 分类列表

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  await getCategoryList()
}

/** 获取分类列表 */
const getCategoryList = async () => {
  loading.value = true
  try {
    const data = await getBookCategories()
    categoryList.value = data
  } finally {
    loading.value = false
  }
}

/** 分类表单操作 */
const categoryFormRef = ref()
const openCategoryForm = (type: string, row?: any) => {
  if (type === 'update' && row) {
    // 设置表单数据
    categoryFormRef.value.open(type, row.id)
    // 需要手动设置表单数据
    nextTick(() => {
      categoryFormRef.value.formData.name = row.name
      categoryFormRef.value.formData.description = row.description
    })
  } else {
    categoryFormRef.value.open(type)
  }
}

/** 删除分类 */
const handleDeleteCategory = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteBookCategory(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getCategoryList()
  } catch {}
}

/** 暴露给父组件的方法 */
defineExpose({ open })
</script>